package com.canbot.u05.activity.editmodule;

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.canbot.u05.R;
import com.canbot.u05.bean.AppInfo;
import com.iflytek.cloud.thirdparty.T;

import java.util.ArrayList;
import java.util.List;

public class AppInfoSelctAdapter extends RecyclerView.Adapter<AppInfoSelctAdapter.Vh>{

    private static final String TAG = "AppInfoSelctAdapter";
    private AppInfoUnSelctAdapter unSelectAdapter;
    private final String[] orderModuleNames;
    private final TypedArray drawableArray;
    private int layoutId;

    private Context context;
    public ArrayList<AppInfo> appInfos;
    private AlertDialog dialog;
    private boolean  isEdited = false; //是否编辑过

    public AppInfoSelctAdapter(Context context, ArrayList<AppInfo> stringList,int layoutId) {
            this.context = context;
            this.appInfos = stringList;
            orderModuleNames = context.getResources().getStringArray(R.array.order_edit_module_names);
            drawableArray = context.getResources().obtainTypedArray(R.array.order_edit_module_drawables);
        this.layoutId = layoutId;
    }

        public void setUnselectAdapter(AppInfoUnSelctAdapter unSelectAdapter){

            this.unSelectAdapter = unSelectAdapter;
        }

        public void setDatas(ArrayList<AppInfo> appInfos){
            this.appInfos = appInfos;
            notifyDataSetChanged();
        }

        public boolean hasEdit(){
            return isEdited;
        }


        public ArrayList getAllAppInfos(){
            ArrayList<AppInfo> arrayList = new ArrayList();

            ArrayList<AppInfo> datas = unSelectAdapter.getdatas();

            arrayList.addAll(appInfos);
            arrayList.addAll(datas);

            return arrayList;

        }


        @Override
        public AppInfoSelctAdapter.Vh onCreateViewHolder(ViewGroup parent, int viewType) {
            return new Vh(LayoutInflater.from(context).inflate(layoutId,null));
        }

        @Override
        public void onBindViewHolder(AppInfoSelctAdapter.Vh holder, final int position) {


            appInfos.get(position).setPosition(position);

            AppInfo appInfo = appInfos.get(position);
            String nickname = appInfo.getNickname();
            String appName = appInfo.getAppName();
            String showName = TextUtils.isEmpty(nickname) ? appName : nickname;

            Log.e(TAG,"appName:" + appName + " nickname:" + nickname);

            holder.tv.setText(showName);

            //通过appname获取图标对应的索引位置
            int orderIndex = calculateOrderIndex(appName);

            Log.e(TAG,"orderIndex:" + orderIndex);

            Drawable drawable = context.getResources().getDrawable(drawableArray.getResourceId(orderIndex, 0));

            holder.iv.setImageDrawable(drawable);

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View view) {
                     remove(position);
                 }
             });

            String tag = (String) holder.tv.getTag();
            if (!TextUtils.isEmpty(tag)){
                holder.tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        showEditAppInfoDialog(position);
                    }
                });
            }
        }

    private void showEditAppInfoDialog(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.item_dialog_edit_module, null);
        RelativeLayout dialogContainer = view.findViewById(R.id.rl_container);
        final EditText etNewName = view.findViewById(R.id.et_new_name);
        final EditText etKeyword01 = view.findViewById(R.id.et_keyword01);
        final EditText etKeyword02 = view.findViewById(R.id.et_keyword02);
        final EditText etKeyword03 = view.findViewById(R.id.et_keyword03);

        builder.setView(view);
        dialog = builder.create();

        view.findViewById(R.id.btn_dialog_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.btn_dialog_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handleEdit(etNewName, etKeyword01, etKeyword02, etKeyword03,position);
            }
        });

        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        //获取屏幕宽高
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = wm.getDefaultDisplay();
        int screenWidth = defaultDisplay.getWidth();
        int screenHeight = defaultDisplay.getHeight();
        ViewGroup.LayoutParams layoutParams = dialogContainer.getLayoutParams();
        layoutParams.height = (int) (screenHeight * 0.8);
        dialogContainer.setLayoutParams(layoutParams);

        //设置dialog宽度
        Window window = dialog.getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        window.setLayout(1200, attributes.height);
        attributes.y = 164;
        window.setGravity(Gravity.TOP);
        //设置dialog背景为透明色
        window.setBackgroundDrawableResource(R.color.transparent);
    }

    private void handleEdit(EditText etNewName, EditText etKeyword01, EditText etKeyword02, EditText etKeyword03, int position) {
        String newName = etNewName.getText().toString();
        String keyword01 = etKeyword01.getText().toString();
        String keyword02 = etKeyword02.getText().toString();
        String keyword03 = etKeyword03.getText().toString();

        if (TextUtils.isEmpty(newName) &&
                TextUtils.isEmpty(keyword01) &&
                TextUtils.isEmpty(keyword02) &&
                TextUtils.isEmpty(keyword03)){

            Toast.makeText(context,"您还没有编辑内容呢", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(newName) && newName.length() < 2){

                Toast.makeText(context,"名称长度不能小于2位数", Toast.LENGTH_SHORT).show();
                return;
        }


        if (!TextUtils.isEmpty(keyword01) && keyword01.length() < 2){

                Toast.makeText(context,"关键字长度不能小于2位数", Toast.LENGTH_SHORT).show();
                return;

        }

        if (!TextUtils.isEmpty(keyword02) && keyword02.length() < 2){

                Toast.makeText(context,"关键字长度不能小于2位数", Toast.LENGTH_SHORT).show();
                return;
        }

        if (!TextUtils.isEmpty(keyword03) && keyword03.length() < 2){

                Toast.makeText(context,"关键字长度不能小于2位数", Toast.LENGTH_SHORT).show();
                return;
        }

        if (!TextUtils.isEmpty(newName)){

            Log.e(TAG,"newName :" + newName);

            appInfos.get(position).setNickname(newName);
        }

        if (!TextUtils.isEmpty(keyword01)){
            appInfos.get(position).setNickname(keyword01);
        }

        if (!TextUtils.isEmpty(keyword02)){
            appInfos.get(position).setNickname(keyword02);
        }

        if (!TextUtils.isEmpty(keyword03)){
            appInfos.get(position).setNickname(keyword03);
        }

        isEdited = true;
        dialog.dismiss();
        notifyDataSetChanged();
    }

    private int calculateOrderIndex(String name) {
        for (int i = 0; i < orderModuleNames.length; i++) {
            if (name.equals(orderModuleNames[i])){
                return i;
            }
        }

        return 0;
    }

    @Override
        public int getItemCount() {
            return appInfos.size();
        }

        public void add(AppInfo item){
            int position = appInfos.size();
            appInfos.add(item);
            notifyItemInserted(position);
            isEdited = true;
        }

        public void add(int position,AppInfo item){
            appInfos.add(position,item);
            notifyItemInserted(position);
            isEdited = true;
        }

        /**
         * 添加至未选中列表（其他功能）再删除选中列表（我的功能）中的数据
         * @param position
         */
        public void remove(int position) {
            if (unSelectAdapter != null){
                AppInfo info = appInfos.get(position);
                info.setMainFunction(false);
                info.setPosition(-1);
                unSelectAdapter.add(info);
                unSelectAdapter.notifyItemInserted(unSelectAdapter.getItemCount());
            }

            appInfos.remove(position);
            /*notifyItemRemoved(position);
            notifyItemRangeChanged(position,appInfos.size() - position);*/
            notifyDataSetChanged();
            isEdited = true;
        }

        class Vh extends RecyclerView.ViewHolder {

            public Vh(View itemView) {
                super(itemView);
                this.itemView = itemView;
                tv = itemView.findViewById(R.id.tv);
                ivDelete = itemView.findViewById(R.id.iv_delete);
                iv = itemView.findViewById(R.id.iv);
            }
            public TextView tv;
            public ImageView iv;
            public ImageView ivDelete;
            public View itemView;
        }
    }